<template>
  <div class="wrap">
    <div class="card-header">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-card class="header-card today-card">
            <div class="title">{{ $t('data.totalUsers') }}</div>
            <div class="num">{{ cardNumber.userNum }}</div>
            <div class="item">
              <span>{{ $t('data.totalStores') }}：</span>
              <span class="item-num">{{ cardNumber.accountNum }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="header-card yesterday-card">
            <div class="title">{{ $t('data.totalLabelRevenue') }}</div>
            <div class="num">{{ cardNumber.stickerIncome }}</div>
            <div class="item">
              <span>{{ $t('data.Total number of label') }}：</span>
              <span class="item-num">{{ cardNumber.stickerNum }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" v-if="false">
          <el-card class="header-card user-card">
            <div class="title">{{ $t('data.Total warehousing revenue') }}</div>
            <div class="num">{{ cardNumber.storageIncome }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="header-card user-card">
            <div class="title">{{ $t('data.总其他收入') }}</div>
            <div class="num">{{ cardNumber.totalOtherIncome }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="header-card income-card">
            <div class="title">{{ $t('data.Total income') }}</div>
            <div class="num">{{ cardNumber.income }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="content-table">
      <el-tabs v-model="tab" @tab-click="handleClick">
        <el-tab-pane :label="$t('data.Date dimension')" name="date"></el-tab-pane>
        <el-tab-pane :label="$t('data.User dimension')" name="user"></el-tab-pane>
        <el-tab-pane :label="$t('data.Platform dimension')" name="platform" v-if="$store.getters.platformNum > 1"></el-tab-pane>
      </el-tabs>
      <div class="table">
        <div class="search">
          <div class="left">
           <diy-date style="display: inline-block;margin-right: 20px" v-model="queryParams.times" @change="getData()" :set-api-times="1" :set-day-type="30" :disdisabled="loading"></diy-date>
          </div>
          <div class="right">
            <div style="display: inline-block;margin-right: 20px;width: 320px" v-if="tab === 'user'">
              <el-input
                size="small"
                style="width: 250px; margin-right: 10px; margin-bottom: 10px"
                v-model="queryParams.keyword"
                placeholder="搜索 店铺或用户名"
                @keyup.enter.native="getData(true)"
                clearable @clear="getData(false, 'clear')"></el-input>
              <el-button size="small" type="primary" @click="getData(true)">{{$t('common.search')}}</el-button>
            </div>
          </div>
        </div>
        <div v-show="tab === 'date'">
          <el-table
            :data="dateData"
            :border="true"
            v-loading="loading"
            stripe
            show-summary
            v-tableHeight="{bottomOffset: 30}"
            height="100px"
            ref="tableDate"
          >
            <el-table-column
              prop="date"
              :label="$t('table.date')"
              align="center"
              min-width="100"
              fixed
            >
            </el-table-column>
            <el-table-column
              prop="orderNum"
              :label="$t('table.Number of newly added stickers')"
              align="center"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="stickerNum"
              :label="$t('table.stickerNumber')"
              align="center"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="stickerIncome"
              :label="$t('table.Total revenue from stickers')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="spStickerPrice"
              :label="$t('table.Income from agency stickers')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="stickerAppend"
              :label="$t('table.Continuation income')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="logisticTypePrice"
              :label="$t('table.Special courier revenue')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="packagePrice"
              :label="$t('table.Packaging service revenue')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumShipmentIncome"
              :label="$t('table.理货总收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="listingFee"
              :label="$t('table.上架收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="combinationFee"
              :label="$t('table.组装收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="bulkCargoIncome"
              label="散货入仓收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="wholeCabinetIncome"
              label="整柜入仓收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="fullInWarehouseIncome"
              label="直送收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumGoodsMiddleIncome"
              :label="$t('table.大货中转总收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="middleIncome"
              :label="$t('table.送仓收入（元）')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="carIncome"
              :label="$t('table.包车收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="transferIncome"
              :label="$t('table.调货收入（元）')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="labelIncome"
              :label="$t('table.贴SKU标收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="labelBoxIncome"
              :label="$t('table.贴外箱标收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumStorageFee"
              :label="$t('仓储收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="totalFee"
              fixed="right"
              :label="$t('table.Total income')"
              align="center"
              min-width="100"
            >
            </el-table-column>
          </el-table>
        </div>


        <div v-show="tab === 'user'">
          <el-table
            :data="userData"
            v-loading="loading"
            :border="true"
            stripe
            show-summary
            :summary-method="getSummaries"
            v-tableHeight="{bottomOffset: 30}"
            height="100px"
            ref="tableUser"
          >
            <el-table-column
              prop="userAccount"
              :label="$t('common.user')"
              align="center"
              fixed
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="accountNum"
              :label="$t('table.Number of stores')"
              align="center"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="orderNum"
              :label="$t('table.Number of newly added stickers')"
              align="center"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="stickerNum"
              :label="$t('table.Number of stickers')"
              align="center"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="stickerIncome"
              :label="$t('table.Total revenue from stickers')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="spStickerPrice"
              :label="$t('table.Income from agency stickers')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="stickerAppend"
              :label="$t('table.Continuation income')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="logisticTypePrice"
              :label="$t('table.Special courier revenue')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="packagePrice"
              :label="$t('table.Packaging service revenue')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumShipmentIncome"
              :label="$t('table.理货总收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="listingFee"
              :label="$t('table.上架收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="combinationFee"
              :label="$t('table.组装收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="bulkCargoIncome"
              label="散货入仓收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="wholeCabinetIncome"
              label="整柜入仓收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="fullInWarehouseIncome"
              label="直送收入（元）"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumGoodsMiddleIncome"
              :label="$t('table.大货中转总收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="middleIncome"
              :label="$t('table.送仓收入（元）')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="carIncome"
              :label="$t('table.包车收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="transferIncome"
              :label="$t('table.调货收入（元）')"
              align="center"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              prop="labelIncome"
              :label="$t('table.贴SKU标收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="labelBoxIncome"
              :label="$t('table.贴外箱标收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="sumStorageFee"
              :label="$t('仓储收入（元）')"
              align="center"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              prop="totalFee"
              fixed="right"
              :label="$t('table.Total income')"
              align="center"
              min-width="100"
            >
            </el-table-column>
          </el-table>
        </div>


        <div v-show="tab === 'platform'">
          <el-table
            :data="platformData"
            v-loading="loading"
            :border="true"
            stripe
            show-summary
            :summary-method="getSummariesPlat"
            v-tableHeight="{bottomOffset: 30}"
            height="100px"
            ref="tablePlatform"
          >
            <el-table-column
              prop="accountType"
              :label="$t('table.platform')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="userNum"
              :label="$t('data.Number of users')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="accountNum"
              :label="$t('table.Number of stores')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="orderNum"
              :label="$t('table.Number of newly added stickers')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="stickerNum"
              :label="$t('table.Number of stickers')"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="stickerIncome"
              :label="$t('table.Income from agency stickers')"
              align="center"
            >
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  accountIndex,
  getDateIncome,
  getIndex,
  getPlatformStatistics,
  getStatisticsInfo,
  getUserIncome
} from "@/api/statistics";
import {dateFormat} from "@/utils/common";
import DiyDate from "@/views/statistics/components/DiyDate.vue";
import platform from "@/views-example/example/components/Dropdown/Platform.vue";

export default {
  name: "incomeReport",
  components: {DiyDate},
  computed:{
    platform() {
      return platform
    },
    tableData(){
      const tableData = [];
      this.data.forEach(item=>{
        if(this.queryParams.showType === 1){
          if(item.orderNum === 0 && item.stickerNum === 0 && item.totalPrice === 0){
            return
          }
        }
        tableData.push(item)
      })
      return tableData;
    },
    tableAccountData(){
      const tableData = [];
      this.accountData.forEach(item=>{
        if(this.queryParams.showType === 1){
          if(item.orderNum === 0 && item.stickerNum === 0 && item.cost === 0){
            return
          }
        }
        tableData.push(item)
      })
      return tableData;
    }
  },
  data(){
    return {
      queryParams:{
        times:[], // 日期
        keywords:'', // 搜索关键字
      },
      cardNumber: {
        userNum: 0,
        accountNum: 0,
        stickerIncome: 0,
        stickerNum: 0,
        storageIncome: 0,
        income: 0,
        totalGoodsMiddleIncome: 0, // 大货
        totalOtherIncome: 0, // 总其他收入
      }, // 卡片数值
      minDate: null,
      // 日期选项
      dateData: [

      ],
      userData: [

      ],
      platformData: [

      ],
      info: {

      },
      accountNum: 0,
      loading:false,

      tab: 'date',
      is_search: false,
    }
  },
  created() {
    const date = new Date()

    let endTime = dateFormat('yyyy-MM-dd',date)
    date.setDate(date.getDate() - 30)
    let startTime = dateFormat('yyyy-MM-dd',date)

    this.queryParams.times = [startTime,endTime]

    this.getCardNum();
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableDate'].doLayout();
      this.$refs['tableUser'].doLayout();
      this.$refs['tablePlatform'].doLayout();
    })
  },
  methods:{
    getCardNum(){
      getStatisticsInfo()
        .then(res=>{
          const { data } = res
          this.cardNumber.userNum = data.user.userNum
          this.cardNumber.accountNum = data.user.accountNum
          this.cardNumber.stickerIncome = data.stickerIncome.totalIncome
          this.cardNumber.stickerNum = data.stickerIncome.num
          this.cardNumber.storageIncome = data.storageIncome
          this.cardNumber.income = data.totalIncome
          this.cardNumber.totalGoodsMiddleIncome = data.totalGoodsMiddleIncome
          this.cardNumber.totalOtherIncome = data.totalOtherIncome
        })
    },
    // 切换tab
    handleClick(){
      this.getData()
    },
    disableFunc(time){
      return true
    },
    getData(is_search = false, type = ''){
      if (is_search === true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type === 'clear') {
        if (this.is_search === false) {
          return
        } else {
          this.is_search = false
        }
      }

      if(this.queryParams.times === null || this.queryParams.times.length === 0){
        this.data = [];
        return;
      }
      this.loading = true
      if(this.tab === 'date'){
        getDateIncome(this.queryParams)
          .then(res=>{
            this.loading = false
            this.dateData = res.data
          })
      }
      if(this.tab === 'user'){
        getUserIncome(this.queryParams)
          .then(res=>{
            this.loading = false
            this.userData = res.data
          })
      }
      if(this.tab === 'platform'){
        getPlatformStatistics(this.queryParams)
          .then(res=>{
            this.loading = false
            this.platformData = res.data
            this.info = res.info
          })
      }
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);

        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    getSummariesPlat(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('table.sum');
          return;
        }
        if( index  === 1){
          sums[index] = this.info.totalUserNum || 0
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);

        } else {
          sums[index] = '-';
        }
      });

      return sums;
    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.calMergeCell(this.userData)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    calMergeCell(tableData){
      const mergeObj = {}; // 用来记录需要合并行的下标

      // 根据userId合并的字段
      const mergeArr = [
        'storageFee', // 订单id
        'userId',
      ];



      mergeArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let userIdKey = 0;
      tableData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suit_id 合并
        if(item.userId === tableData[index - 1].userId){
          mergeArr.forEach(key=>{
            mergeObj[key][userIdKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          userIdKey = index; // 记录当前行
          mergeArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

      })

      return mergeObj
    },

  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
}
.today-card{
  background: inherit;
  background-color: #4A89DC;
}
.yesterday-card{
  background: inherit;
  background-color: #5D9CEC;
}
.user-card{
  background: inherit;
  background-color: #3bafda;
}
.income-card{
  background: inherit;
  background-color: #7db1b1;
}
.header-card{
  color: #FFFFFF;
  font-size: 14px;
  height: 150px;
  .title{
    font-weight: 400;
    font-style: normal;
    color: #FFFFFF;
  }
  .num{
    font-size: 36px;
    font-weight: 500;
    margin: 10px 0;
  }
  .item{
    font-size: 12px;
    font-weight: 400;
    margin-bottom: 10px;
    .item-num{
      color: #FFCD00;
    }
  }
}
.content-table{
  margin-top: 20px;

  .table{
    .search{
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }
  }
}
</style>
